<template>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <Teleport to="body" >
<!--自动聚焦问题待解决，准备尝试用js手动聚焦-->
    <!-- 浮动输入框 -->
        <div v-if="showNameInput==true" class="floating-input-wrapper"  >
            
            <div class="floating-input-top">
                <div style="width: 14px;height: 14px;"></div><div class="floating-input-title">中药名</div><img src="../assets/Vector.svg" @click="showNameInput=false"/>
            </div>
            <input autofocus
            v-model="medicineAdd.medicine_name" 
            type="text" 
            placeholder="请输入内容" 
            class="floating-input"
            ref="floatingInput"
            />
            <hr>
            <div class="floating-input-ok" @click="showNameInput=false" :style="{backgroundColor:nameTrueColor}">确定</div>
        </div>
    </Teleport>
    <Teleport to="body" >

    <!-- 浮动输入框 -->
        <div v-if="showTropismInput==true" class="floating-input-wrapper" >
            
            <div class="floating-input-top">
                <div style="width: 14px;height: 14px;"></div><div class="floating-input-title">性味归经</div><img src="../assets/Vector.svg" @click="showTropismInput=false"/>
            </div>
            <input autofocus
            v-model="medicineAdd.tropism" 
            type="text" 
            placeholder="请输入内容" 
            class="floating-input"
            ref="floatingInput"
            />
            <hr>
            <div class="floating-input-ok" @click="showTropismInput=false" :style="{backgroundColor:tropismTrueColor}">确定</div>
        </div>
    </Teleport>
    <Teleport to="body" >

<!-- 浮动输入框 -->
    <div v-if="showFunctionsInput==true" class="floating-input-wrapper" >
        
        <div class="floating-input-top">
            <div style="width: 14px;height: 14px;"></div><div class="floating-input-title">功能主治</div><img src="../assets/Vector.svg" @click="showFunctionsInput=false"/>
        </div>
        <input autofocus
        v-model="medicineAdd.functions" 
        type="text" 
        placeholder="请输入内容" 
        class="floating-input"
        ref="floatingInput"
        />
        <hr>
        <div class="floating-input-ok" @click="showFunctionsInput=false" :style="{backgroundColor:functionTrueColor}">确定</div>
    </div>
    </Teleport>
    
    
    <div class="root">
        <div class="head">
            <img src="../assets/x.svg" @click="toMedicineList()" style="width: 52px;"/>
            <h2 class="mdc-tital" @click="">添加中药</h2>
            <div style="width: 65px;height: 52px;"></div>
        </div>
        <div class="content">
            <div style="height: 65px;"></div>
            <div class="tital-2">基础信息</div>
         
            <div class="input-box-1">
                <div style="height: 6px;"></div>
                <div class="item-name " @click="showNameInput = true" >

                    <div>中药名</div><div class="input-button" >{{ returnedMedicineName }}</div>
                </div>
                <hr>
                <div class="img-box">
                    <div>中药图片</div>
                    <div hidden class="upload-img" >
                        <!--需要加入选择图片后显示图片，然后在点击添加中药时再上传-->
                        <img :src="medicineAdd.image_url"  style="width: 85px;height: 85px;" v-if="isUpload">
                        <label   transform >
                            <input type="file" hidden @change="upLoadFile" />
                        </label>
                            <img :hidden="!isLoading" src="../assets/Spinner@1x-1.0s-200px-200px.svg" width="85px"/>
                            <img :hidden="isUpload|| isLoading" style="width: 24px;" src="../assets/Frame.svg"/>
                            <div :hidden="isUpload|| isLoading" style="height: 6px;"></div>
                            <div :hidden="isUpload|| isLoading" class="upload-img-f">上传图片</div>
                        
                    </div>
                </div>
                
            </div>
            <!--<div class="img-input">
                <input type="file" @change="upLoadFile" />
                

                未完工，测试用<br>
                图片url:<input class="item-img" v-model="medicineAdd.image_url"/>
            </div>-->
            <div style="height: 18px;"></div>
            <div class="tital-2">描述</div>
            <div class="input-box-2">
                <div style="height: 10px;"></div>
                <div class="item-name-descrip ">
                    <textarea class="descrip-input" type="text" v-model="medicineAdd.description" placeholder="请填写中药的具体描述"/>
                </div>
            </div>
            <div style="height: 8px;"></div>
            <div class="input-box-1">
                <div style="height: 6px;"></div>
                
                <div class="item-name " @click="showTropismInput = true">
                    <div>性味归经</div><div class="input-button">{{returnedTropism}}</div>
                </div>
                <hr>
                <div class="item-name " @click="showFunctionsInput = true">
                    <div>功能主治</div><div class="input-button">{{returnedDescription}}</div>
                </div>
                <div style="height: 6px;"></div>
            </div>
            <div style="height: 200px;"></div>

            
            
        </div>
        <div class="bottom">
            <div class="add-button" @click="addMedicine" >添加</div>
        </div>

    </div>   

</template>


<script setup lang="ts" >


import {ref,Teleport,watch} from 'vue'
import router from '../router';

//浮动输入框
const showNameInput = ref(false); // 控制输入框显示
const showTropismInput = ref(false)
const showFunctionsInput = ref(false)


    // 显示输入框后自动聚焦
 //   watch(showInput, (newVal) => {
   //   if (newVal && floatingInput.value) {
  //      floatingInput.value
   //   }
 //   });

    // 隐藏输入框
 //   const hideInput = () => {
  //    showInput.value = false;
 //   };


//上传图片
//获取token
const getToken =async()=>{
    const response = await fetch('/api/upload_token')
    const data = await response.json()
    const token = data['data']
    console.log(token);
    return token
}
//通过图片本地地址上传文件
const isLoading = ref(false)
const isUpload = ref(false)
const upLoadFile = async(event:any)=>{
    isLoading.value = true
    const file = event.target.files[0]; 
    const token = await getToken();
    //生成fromData
    const formData = new FormData();
    formData.append('token', token);
    formData.append('file', file);
    try{
        console.log('isLoading',isLoading.value);
        const response = await fetch('http://upload.qiniup.com/', {
            method: 'POST',
            headers: {
              'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
              'Accept': '*/*',
              'Host': 'upload.qiniup.com',
              'Connection': 'keep-alive',
              // 注意：当使用FormData时，浏览器会自动设置正确的Content-Type，不需要手动指定multipart/form-data相关详细的boundary内容
            },
            body: formData
          });

        const result = await response.json();
        console.log('上传结果:', result);
        //拼接字符串得到图片的url
        medicineAdd.value.image_url = 'http://images.hskstudy.fun/'+result.key
        console.log(medicineAdd.value.image_url);

        //检测是否有输入图片
        isLoading.value=false
        console.log('isLoading',isLoading.value);
        isUpload.value = true
        console.log('isUpload',isUpload.value);
        
        return isUpload 
        
        
    }catch (error) 
    {
        console.error('上传出现错误:', error);
    }
}



//定义
interface medicine {
  medicine_name: string,
  image_url: string,
  description: string,
  tropism:string,//性味归经
  functions:string,//功能主治
}
//初始化
let medicineAdd = ref<medicine>({
    medicine_name: '',
    image_url: '',
    description: '',
    tropism: '',
    functions: ''
})


//提交数据

const addMedicine = async()=>{
    if( //检测是否填写完整
        medicineAdd.value.medicine_name.trim()===''||
        medicineAdd.value.image_url.trim()===''||
        medicineAdd.value.description.trim()===''||
        medicineAdd.value.tropism.trim()===''||
        medicineAdd.value.functions.trim()===''){
            alert('未输入完整')
        }else{
    
    try{//post请求
        const response = await fetch('/api/add_medicine',
        {
            method:'POST',
            headers:{
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(medicineAdd.value)
            
        });
        const data = await response.json();
        console.log(data);
        //数据清除
        medicineAdd.value = {
        medicine_name:'',
        image_url:'',
        description:'',
        tropism:'',
        functions:''
        }
        isUpload.value = false
        toMedicineList()
        return isUpload
        

    }catch (error){
        console.error(error);
    }}
}
//回到上一级
const toMedicineList = () => {
    router.push('/medicineList');
};

const nameTrueColor = ref('')
const returnedMedicineName = ref('请输入 >')
const returnedTropism = ref('请输入 >')
const returnedDescription = ref('请输入 >')
//监听是否有输入name
watch( ()=> medicineAdd.value.medicine_name,
    (newValue) => {
        console.log(newValue);
        if(newValue.trim()!==''){
            nameTrueColor.value ='#868686'
            returnedMedicineName.value = medicineAdd.value.medicine_name
        }else{
            nameTrueColor.value = '#F2F3F5'
            returnedMedicineName.value = '请输入 >'
        }
    }
)
//监听是否有输入tropism
const tropismTrueColor = ref('')
watch( ()=> medicineAdd.value.tropism,
    (newValue) => {
        console.log(newValue);
        if(newValue.trim()!==''){
            tropismTrueColor.value ='#868686'
            returnedTropism.value = '已输入 >'
        }else{
            tropismTrueColor.value = '#F2F3F5'
            returnedTropism.value = '请输入 >'
        }
    }
)
//监听是否有输入description
const functionTrueColor = ref('')
watch( ()=> medicineAdd.value.functions,
    (newValue) => {
        console.log(newValue);
        if(newValue.trim()!==''){
            functionTrueColor.value ='#868686'
            returnedDescription.value ='已输入 >'
        }else{
            functionTrueColor.value = '#F2F3F5'
            returnedDescription.value = '请输入 >'
        }
    }
)
//检测到有输入后，将‘请输入 >’转化为‘输入的内容’
//中药名

</script>

<style scoped>
.upload-img-inside{
    align-items: center;
    justify-content: center;
    flex-direction: column;
}
.floating-input-top{
    display: flex;
    justify-content: space-between;
    width: 90%;
}
.floating-input-title{
    margin: 16px;
    
}
.floating-input-ok{
    background-color: #F2F3F5;
    width: 90%;
    height: 45px;
    border-radius: 3px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 16px;
    margin-bottom: 10px;

}
.floating-input-wrapper{
    z-index: 1000;
    bottom: -13%;
    position: fixed;
    left: 50%; /* 距离左边 50% */
    transform: translate(-50%, -50%); /* 通过位移使元素居中 */
    width: 100%;
    height: 189px;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    border-radius: 6px;
    box-shadow: 5px -5px 10px 2px rgba(0, 0.1, 0.1, 0.1);

}
label{height: 85px;width: 85px;position: absolute;}
h2{
    font-size: 16px;
}
hr{
    width: 95%;
    background-color: #ffffff;
}
.root{max-width: 550px;
    margin: 0 auto;
}
.head{
    display: flex;
   
    height: 50px;
    width: 100%;
    align-items: center;
    box-shadow: 0px 5px 10px 2px rgba(0, 0, 0, 0.04);
    background-color: #fff;
    position: fixed;
    max-width: 550px;
    display: flex;
    justify-content: space-between;
}
.bottom{

    justify-content: center;
    height: 80px;
    width: 100%;
    align-items: center;
    box-shadow: 0px 5px 10px 2px rgba(0, 0, 0, 0.04);
    background-color: #fff;
    position: fixed;
    bottom: 0;
    max-width: 550px;
}
.input-button{
    color: #9498A3;
    font-family: 'PingFang SC';
    font-size: 14px;
    font-weight: 400;
    line-height: 19.6px;
    text-align: left;
    text-underline-position: from-font;
    text-decoration-skip-ink: none;


}
.mdc-title {
    align-self: center;
    font-size: 16px;

}
.mdc-detail{
    width: 350px;
}
.input-box-1{
    
    background-color: #fff;
    
    box-shadow: 2px 2px 15px 1px rgba(0, 0, 0, 0.04);

    border-radius: 6px;
    margin-left: 6px;
    margin-right: 6px;
    margin-top: 12px;
}
.input-box-2{
    
    background-color: #fff;
    
    box-shadow: 2px 2px 15px 1px rgba(0, 0, 0, 0.04);

    border-radius: 6px;
    margin-left: 6px;
    margin-right: 6px;
    margin-top: 12px;
}
.no-outline{
    border: none; /* 去掉边框 */
    outline: none; /* 去掉点击时的轮廓线 */
}
.img-box{
    margin-left: 12px;
    margin-right: 12px;
    margin-top: 16px;
    align-items: flex-start;
    display: flex;
    justify-content:space-between
}
.img-input{
    background-color: #fff;
    height: 170px;
    box-shadow: 2px 2px 15px 1px rgba(0, 0, 0, 0.04);

    border-radius: 6px;
    margin-top: 20px;
    margin-left: 6px;
    margin-right: 6px;
}
.add-button{
    background-color: #868686;
    height: 46px;
    box-shadow: 2px 2px 15px 1px rgba(0, 0, 0, 0.04);

    border-radius: 36px;
    margin-top: 20px;
    margin-left: 12px;
    margin-right: 12px;
    margin-bottom: 6px;

    font-size: 24px;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    font-family: 'PingFang SC';
font-size: 14px;
font-weight: 400;
line-height: 19.6px;


}
.content{

}
.item-name{
    margin-left: 12px;
    margin-right: 12px;
    height: 40px;
    align-items:center;
    display: flex;
    justify-content:space-between
}
.item-name-descrip{
    margin-left: 12px;
    margin-right: 12px;
    height: 110px;
    align-items:flex-start;
    display: flex;
    justify-content:space-between

}
.item-input{
    height: 40px;
    margin-top: 6px;
    width: 210px;
    margin-left: 50px;
    margin-bottom: 6px;
    

}
.item-img{
    height: 50px;
    width: 210px;
    
}
.tital-2{
    font-family: 'PingFang SC';
    font-size: 16px;
    font-weight: 500;
    margin-left: 8px;
    
}
.upload-img{
    background-color: #D9D9D9;
    width: 85px;
    height: 85px;
    margin-bottom: 20px;
    display: flex;
    justify-content:center;
    flex-direction:column;
    align-items: center;
    
}
.upload-img-f{
    font-family: 'PingFang SC';
    font-size: 12px;
    font-weight: 400;
    line-height: 16.8px;
    letter-spacing: -0.02em;
    text-align: left;
    text-underline-position: 'from-font';
    text-decoration-skip-ink: none;

}
.descrip-input{
    all: unset;
    height: 110px;
    width: 100%;
}
.floating-input{
    width: 87%;
    height: 50px;
    border: none; /* 无边框 */
    outline: none; /* 取消聚焦时的外边框 */
    font-size: 15px;
}
</style>
